using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace PluginHandler.Database
{
    class DatabaseTable : IDatabaseTable
    {
        private DatabaseHandler _databaseHandler;
        private string _name;
        private List<IDatabaseTableColumn> _columns;

        internal DatabaseTable(DatabaseHandler databaseHandler, string name)
        {
            _databaseHandler = databaseHandler;

            _name = name;
            _columns = null;
        }

        #region IDatabaseTable Member

        public List<IDatabaseTableColumn> Columns
        {
            get 
            {
                if (_columns == null)
                {
                    _columns = new List<IDatabaseTableColumn>();

                    //***********************************************
                    //***********************************************
                    //TODO: Implement the listed columns by using the database handler reference
                    //e.g.:
                    System.Data.DataTable dataTable = GetTableSchema();

                    foreach (System.Data.DataRow dataRow in dataTable.Rows)
                    {
                        string columnName = dataRow["COLUMN_NAME"].ToString();
                        DbType dataType = DatabaseTableColumn.ConvertStringToDbType(dataRow["DATA_TYPE"].ToString());
                        string schemaType = dataRow["DATA_TYPE"].ToString();

                        _columns.Add(
                            new DatabaseTableColumn(_databaseHandler, this, columnName, dataType, schemaType));
                    }
                    //***********************************************
                    //***********************************************
                }

                return _columns;
            }
        }

        #endregion

        #region IDatabaseObject Member

        public string Name
        {
            get { return _name; }
        }

        public DataTable GetTableSchema()
        {
            //***********************************************
            //***********************************************
            //TODO: Implement the complete schemainformation by using the database handler reference
            //e.g.:
            System.Data.SqlClient.SqlConnection sqlConnection = (System.Data.SqlClient.SqlConnection)_databaseHandler.DatabaseConnection;
            System.Data.DataTable schemaInformation = sqlConnection.GetSchema(
                "Columns",
                new string[] 
                { 
                    null, 
                    null, 
                    _name
                });

            return schemaInformation;
            //***********************************************
            //***********************************************
        }

        #endregion
    }
}
